<template>
  <page-meta :root-font-size="fontsize" style="display: block">
    <div class="findWork">
      <xlNavBar :isShare="isShare" :title="isPageTitleFind == 1 ? '找工作' : '招员工'" bgc="ff9d49" :showCheck="true" @checkModel="checkModel"></xlNavBar>
      <div class="tabs">
        <u-tabs
          :list="tabList"
          :lineColor="tabLineColor"
          :current="tabActiveIndex"
          :activeStyle="{
            fontSize: '16px',
            fongWeight: '800',
            color: tabLineColor,
          }"
          :inactiveStyle="{ fontSize: '14px' }"
          @change="tabChange"
        ></u-tabs>
        <div class="right">
          <div v-if="tabActiveIndex != 1" class="item address" @click="showCityPopup = true">
            <span>
              {{ getSelectCity[0]["fullname"] || "全国" }}
              {{ getSelectCity.length ? "·" + getSelectCity.length : "" }}
            </span>
            <i class="iconfont cyyouxia"></i>
          </div>
          <div class="item screening" @click="clickSx">
            <span>筛选{{ wangJob ? "·" + wangJob : "" }}</span>
            <i class="iconfont cyyouxia"></i>
          </div>
        </div>
      </div>
      <loadFail
        height="77vh"
        @click="startLocation"
				src="https://canyinxinxi.cn/dist_img/WechatIMG5145.jpg"
        v-if="!getUserLocationInfo && tabActiveIndex == 1"
        text="您当前未开启定位，请开启定位后在进入该页面"
        btnText="开启定位"
      ></loadFail>
      <div class="tab-content" v-else-if="dataList && dataList.length > 0">
        <scroll-view class="scrollView" scroll-y height="84vh" @scrolltolower="lowerBottom" @scroll="scroll" @refresherrefresh="getFresh">
          <div class="wrap" v-if="isPageTitleFind">
            <jobItem v-for="(item, index) in dataList" :key="index" :data="item" itemType="1" type="3" titleTagText="招聘" btnText="联系老板"></jobItem>
          </div>
          <div class="wrap" v-else>
            <resumeItem v-for="(item, index) in dataList" :key="index" :data="item" :itemType="2" type="3" titleTagText="求职" btnText="联系对方"></resumeItem>
          </div>
        </scroll-view>
      </div>

      <loadFail height="77vh" @click="getList(true)" v-else text="暂时没有数据，请切换城市后尝试"></loadFail>
      <div class="bottom_btn_wrap">
        <image
          v-if="getUserInfo"
          class="button"
          @click="
            toPostPage(
              isPageTitleFind == 1
                ? !getUserStatus.resume_status
                  ? '/pages2/postRecruitmentInformation'
                  : '/pages2/regulateResume'
                : !getUserStatus.job_status
                ? '/pages2/postOffer'
                : '/pages2/regulateJobs'
            )
          "
          :src="
            isPageTitleFind == 1
              ? !getUserStatus.resume_status
                ? '/pages2/static/images/mffbqz.png'
                : '/pages2/static/images/glqzxq.png'
              : !getUserStatus.job_status
              ? '/pages2/static/images/mffbzg.png'
              : '/pages2/static/images/glzpxq.png'
          "
          mode="scaleToFill"
        />
        <button v-else open-type="getPhoneNumber" @getphonenumber="getphonenumberLogin">
          <image
            class="button"
            :src="
              isPageTitleFind
                ? !getUserStatus.job_status
                  ? '/pages2/static/images/mffbqz.png'
                  : '/pages2/static/images/glqzxq.png'
                : !getUserStatus.resume_status
                ? '/pages2/static/images/mffbzg.png'
                : '/pages2/static/images/glzpxq.png'
            "
            mode="scaleToFill"
          />
        </button>
      </div>

      <u-popup v-if="!getUserInfo && showPopup" :show="showPopup" :round="10" mode="bottom" :closeable="true" @close="closePopup" @open="openPopup">
        <view class="popup-content">
          <div class="title">请选择您的需求</div>
          <div class="content">
            <div class="item item2">
              <button class="btn" v-if="getUserInfo" @click="goListPage(2)"></button>
              <button class="btn" v-else open-type="getPhoneNumber" @getphonenumber="getPhoneNumberZyg"></button>
            </div>
            <div class="item item1">
              <button class="btn" v-if="getUserInfo" @click="goListPage(1)"></button>
              <button class="btn" v-else open-type="getPhoneNumber" @getphonenumber="getPhoneNumberFindJob"></button>
            </div>
          </div>
        </view>
      </u-popup>

      <selectCityPopup v-if="showCityPopup" type="select" @getData="getCityDataList" :max="3" :show="showCityPopup" @submit="getCityInfo"></selectCityPopup>
      <selectJobPopup v-if="showJobPopup" :show="showJobPopup" @submit="getJobList"></selectJobPopup>
    </div>
  </page-meta>
</template>

<script>
import loadFail from "@/pages2/components/common/loadFail.vue";
import jobItem from "@/pages2/components/common/jobItem.vue";
import resumeItem from "@/pages2/components/common/resumeItem.vue";
import selectCityPopup from "@/pages2/components/popup/selectCityPopup.vue";
import selectJobPopup from "@/pages2/components/popup/selectJobPopup.vue";
import { mapActions, mapGetters, mapMutations } from "vuex";
export default {
  name: "findWork",
  components: {
    jobItem,
    resumeItem,
    selectCityPopup,
    selectJobPopup,
    loadFail,
  },
  props: {},
  data() {
    return {
      showPage: false,
      isShare: 0,
      fontsize: "",
      userStatus: null,
      showCityPopup: false,
      showJobPopup: false,
      showPopup: false,
      isPageTitleFind: true,
      tabLineColor: "#ff9d49",
      isLogin: false,
      tabActiveIndex: 0,
      // dataCityList: [],
      dataJobList: [],
      tabList: [
        {
          name: "推荐",
        },
        {
          name: "附近",
        },
        {
          name: "最新",
        },
      ],
      postParams: {
        type: 1, //列表类型 1、推荐，2、附近、3、最新
        // filter: 3, //过滤条件
        Filter: {
          // city_codes: "110000", // 城市筛选，多个逗号间隔  默认空
          city_codes: "", // 城市筛选，多个逗号间隔  默认空
          //传选中城市的层级ID（比如选中河北石家庄，则传 130000,130100）
          job_intention: "", // 岗位，多个逗号间隔
        },
        // longitude: 0, //经度
        // latitude: "", //经度
        page_num: 1, // 页码
        page_size: 20, // 每页个数
      },
      dataList: [],
      code: "",
      // 完成
      finish: false,
    };
  },
  async created() {
    let city_codes = [];
    this.getSelectCity.forEach(item => {
      city_codes.push(item.id);
    });
    this.postParams.Filter.city_codes = city_codes.join(",");
    this.postParams.Filter.job_intention = this.$store.state.jobIntention;
    // this.getList(true);

    if (!this.$getStoraged("showFindPopup")) {
      this.showPopup = true;
    }
  },
  computed: {
    ...mapGetters("location", ["getSelectCity", "getCurProvince", "getUserLocationInfo"]),
    ...mapGetters("user", ["getUserStatus", "getUserInfo", "getPhone"]),
    ...mapGetters(["getJobIntention"]),
    wangJob() {
      if (this.getJobIntention) {
        if (this.getJobIntention.indexOf(",")) {
          return this.getJobIntention.split(",").length;
        } else {
          return 1;
        }
      } else {
        return 0;
      }
    },
    dataCityList() {
      let arr = [];
      if (this.getSelectCity.length) {
        this.getSelectCity.forEach(item => {
          arr.push(item.id);
        });
      }
      this.postParams.Filter.city_codes = arr.join(",");
      return this.getSelectCity || [this.getCurProvince];
    },
  },
  async mounted() {
    await this.setStatus();
  },
  methods: {
    ...mapActions("user", ["setUserInfo", "setStatus", "chatLogin"]),
    ...mapMutations("location", ["setUserLocationInfo", "setSelectCity"]),
    async getphonenumberLogin(e) {
      console.log(111);
      let _this = this;
      this.$throttle(async () => {
        if (e.detail.errMsg === "getPhoneNumber:ok") {
          //这里受机型与模拟器影响，errmsg信息各不相同，只能判断用户是否点击了允许按钮来判断，
          console.log("用户允许授权");
          // code...
          await this.chatLogin({ code: e.detail.code, deviceModel: this.device_model, type: this.isPageTitleFind == 1 ? "resume" : "job" });
        } else {
          //如果没有走以上，均为点击了拒绝授权
          console.log("用户拒绝授权");
          uni.showToast({
            title: "登录授权已取消",
            icon: "error",
            mask: true,
          });
          // 通常会在这里弹出模态框，引导用户点击允许授权
        }
      });
    },

    // 开启位置
    async startLocation() {
      console.log("开启定位");
      let res = await this.$getLocationPromise();
      if (res) {
        let res2 = await this.$http.request("https://apis.map.qq.com/ws/geocoder/v1/?key=6KJBZ-ZB2W4-NXNUB-DT7KO-E4KMJ-7KB5L&location=" + res.latitude + "," + res.longitude, "GET", {}, data => {
          this.setUserLocationInfo(data.result); //保存用户位置信息到vuex中，方便在选择地址时直接选择
          this.postParams.Filter.city_codes = data.result.ad_info.adcode;
          this.getList(true);
        });
        this.showLocationTips2 = true;
      } else {
        this.showLocationTips = true;
        console.log(res);
      }
    },
    scroll(e) {
      console.log(e);
    },
    getFresh() {
      console.log("下拉刷新");
    },
    lowerBottom(data) {
      if (!this.finish) {
        this.postParams.page_num = this.postParams.page_num + 1;
        this.getList();
      }
      console.log("触底加载");
    },
    // 我要找工作事件
    getPhoneNumberFindJob(e) {
      let _this = this;
      this.$throttle(async () => {
        if (e.detail.errMsg === "getPhoneNumber:ok") {
          //这里受机型与模拟器影响，errmsg信息各不相同，只能判断用户是否点击了允许按钮来判断，
          console.log("用户允许授权");
          // code...
          await this.chatLogin({ code: e.detail.code, deviceModel: this.device_model, type: "resume" });
        } else {
          //如果没有走以上，均为点击了拒绝授权
          console.log("用户拒绝授权");
          uni.showToast({
            title: "登录授权已取消",
            icon: "error",
            mask: true,
          });
          // 通常会在这里弹出模态框，引导用户点击允许授权
        }
      });
    },
    // 我要招员工事件
    getPhoneNumberZyg(e) {
      let _this = this;
      this.$throttle(async () => {
        if (e.detail.errMsg === "getPhoneNumber:ok") {
          //这里受机型与模拟器影响，errmsg信息各不相同，只能判断用户是否点击了允许按钮来判断，
          console.log("用户允许授权");
          // code...
          await this.chatLogin({ code: e.detail.code, deviceModel: this.device_model, type: "job" });
        } else {
          //如果没有走以上，均为点击了拒绝授权
          console.log("用户拒绝授权");
          uni.showToast({
            title: "登录授权已取消",
            icon: "error",
            mask: true,
          });
          // 通常会在这里弹出模态框，引导用户点击允许授权
        }
      });
    },
    goListPage(type) {
      this.$throttle(() => {
        if (type == 1) {
          //我要找工作
          if (this.$getStoraged("phone").length > 0) {
            this.showPopup = false;
            this.$togo(`/pages2/postRecruitmentInformation`, {
              phone: this.getPhone,
              type: type,
            });
          }
        } else if (type == 2) {
          // 我要招员工
          if (this.$getStoraged("phone").length > 0) {
            this.showPopup = false;
            this.$togo("/pages2/postOffer", {
              phone: this.getPhone,
            });
          }
        }
      }, 500);
    },
    clickSx() {
      this.$throttle(() => {
        this.showJobPopup = true;
      });
    },
    closePopup() {
      this.$throttle(() => {
        this.showPopup = false;
        this.$setStoraged("showFindPopup", 2);
      });
    },
    openPopup() {
      this.$throttle(() => {
        this.showPopup = true;
      });
    },
    checkModel() {
      this.$throttle(() => {
        this.isPageTitleFind = !this.isPageTitleFind;
        this.postParams.page_num = 1;
        this.list = [];
        this.getList(true);
      }, 500);
    },
    tabChange(data) {
      this.$throttle(() => {
        this.tabActiveIndex = data.index;
        switch (data.index) {
          case 0:
            this.tabLineColor = "#ff9d49";
            this.postParams.type = 1;
            this.postParams.page_num = 1;
            break;
          case 1:
            this.tabLineColor = "#ff9d49";
            this.postParams.type = 2;
            this.postParams.page_num = 1;
            if (!this.$getStoraged("userLocationInfo")) this.startLocation();
            break;
          case 2:
            this.tabLineColor = "#ff9d49";
            this.postParams.type = 3;
            this.postParams.page_num = 1;
            break;

          default:
            this.tabLineColor = "#ff9d49";
            this.postParams.page_num = 1;
            break;
        }
        this.getList(true);
        debugger;
        console.log(data);
      }, 500);
    },
    toPostPage(url) {
      this.$throttle(() => {
        let params = {};
        if (this.$getStoraged("phone").length) {
          params.phone = this.getPhone;
        }
        this.$togo(url, params);
      });
    },
    getCityInfo(data) {
      this.$throttle(() => {
        this.showCityPopup = false;
      }, 300);
    },
    async getList(type) {
      if (this.finish) return false;
      if (type) {
        this.dataList = [];
      }
      if (this.tabActiveIndex == 1 && this.getUserLocationInfo) {
        let userLocationInfo = this.getUserLocationInfo;
        this.postParams.longitude = userLocationInfo.ad_info.location.lng; //经度
        this.postParams.latitude = userLocationInfo.ad_info.location.lat; //经度
        this.postParams.distance = 10000; //附近距离
      } else {
        delete this.postParams.distance;
      }
      if (this.tabActiveIndex == 0 || this.tabActiveIndex == 2) {
        this.postParams.longitude = null; //经度
        this.postParams.latitude = null; //经度
      }
      let params = JSON.parse(JSON.stringify(this.postParams));
      if (this.tabActiveIndex == 1) {
        params.Filter.city_codes = "";
      }

      let res = await this.$http.requestSync(this.isPageTitleFind ? "/jobs/list" : "/resumes/list", params);
      // let res = await this.$http.requestSync(this.isPageTitleFind ? "/jobs/list" : "/resumes/list", this.postParams);
      try {
        if (res.code == 200) {
          if (this.isPageTitleFind) {
            res.jobs.forEach(item => {
              if (item && item.photo_urls) {
                item.photo_urls = item.photo_urls.indexOf(",") > -1 ? item.photo_urls.split(",") : [item.photo_urls];
                // this.$set(this.data, "photo_urls", this.urls2);
              }
            });
            this.dataList = [...this.dataList, ...res.jobs];

            if (!res.jobs || res.jobs.length < this.postParams.page_num) {
              this.finish = true;
            }
          } else {
            res.resumes.forEach(item => {
              if (item && item.photo_urls) {
                item.photo_urls = item.photo_urls.indexOf(",") > -1 ? item.photo_urls.split(",") : [item.photo_urls];
                // this.$set(this.data, "photo_urls", this.urls2);
              }
            });
            this.dataList = [...this.dataList, ...res.resumes];
            if (!res.resumes || res.resumes.length < this.postParams.page_num) {
              this.finish = true;
            }
          }
          this.showPage = true;
        } else {
          this.dataList = [];
        }
      } catch (error) {
        this.$layer.message(error);
      }
    },
    getCityDataList(data) {
      this.$throttle(() => {
        this.showCityPopup = false;
        // this.dataCityList = data;
        // console.log("this.dataCityListthis.dataCityList", this.dataCityList, data);
        // this.postParams.Filter.city_codes
        let arr = [];
        data.forEach(item => {
          arr.push(item.id);
          this.postParams.Filter.city_codes = arr.join(",");
        });
        this.postParams.page_num = 1;
        this.getList(true);
      });
    },
    getJobList(data) {
      this.$throttle(() => {
        this.postParams.Filter.job_intention = "";
        this.dataJobList = data;
        let arr = [];
        data.forEach(item => {
          arr.push(item.name);
          this.postParams.Filter.job_intention = arr.join(",");
        });
        this.showJobPopup = false;
        this.getList(true);
      });
    },
  },
  watch: {
    isPageTitleFind: {
      handler(n, o) {
        console.log("isPageTitleFind变化了");
      },
      getJobIntention(n, o) {
        console.log(578, n);
      },
      // immediate: true,
    },
  },

  // 页面周期函数--监听页面加载
  onLoad(options) {
    if (options.params) {
      let params = JSON.parse(decodeURIComponent(options.params));
      if (params.shareUserId) {
        this.$setStoraged("shareUserId", params.shareUserId);
        this.isShare = 1;
      }
    }
    if (options.p == 1) {
      this.showPopup = true;
    }
    console.log("611", options.isPageTitleFind);
    if (options.isPageTitleFind == 2 || options.p == 2) {
      this.isPageTitleFind = false;
    }

    if (this.$getStoraged("postResumAddress").length) {
      this.getCityDataList(JSON.parse(this.$getStoraged("postResumAddress")));
    }

    let designWidth = 37.5; //因设计图的宽度
    let that = this;
    //窗体改变大小触发事件
    uni.onWindowResize(res => {
      console.log("变化后的窗口宽度=", res.size.windowWidth);
      //100*屏幕宽度/设计稿宽度
      that.fontsize = Math.floor((1.5 * res.size.windowWidth) / designWidth) + "px";
      console.log("字体大小：", that.fontsize);
    });

    //打开获取屏幕大小
    uni.getSystemInfo({
      success(res) {
        console.log("设备信息：", res);
        that.fontsize = Math.floor((1.5 * res.screenWidth) / designWidth) + "px";
        console.log("字体大小：", that.fontsize);
      },
    });
    this.getList(true);
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  async onShow(options) {
    // this.tabActiveIndex = 0;
    // this.postParams.page_num = 1;
    // console.log("617", this.postParams.Filter.city_codes);
    // this.postParams.Filter.city_codes = "";
    // let city_codes = [];
    // city_codes = [];
    // this.getSelectCity.forEach(item => {
    //   city_codes.push(item.id);
    // });
    // this.postParams.Filter.city_codes = city_codes.join(",");
    // this.postParams.Filter.job_intention = this.$store.state.jobIntention;
    // setTimeout(() => {
    //   this.getList(true);
    // }, 200);
  },
  // 页面周期函数--监听页面隐藏
  onHide() {
    this.postParams.Filter.city_codes = "";
    this.postParams.Filter.job_intention = "";
    if (this.$getStoraged("postResumAddress").length) {
      this.$removeStoraged("postResumAddress");
    }
  },
  // 页面周期函数--监听页面卸载
  onUnload() {},
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style scoped lang="scss">
.findWork {
  background: #f7f7f7;
  .tabs {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    .right {
      display: flex;
      align-items: center;
      .item {
        display: flex;
        height: 21px;
        box-sizing: border-box;
        padding: 5px;
        background: #f4f4f4;
        border-radius: 4px 4px 4px 4px;
        line-height: 10px;
        font-size: 12px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
        margin-right: 13px;

        .iconfont {
          font-size: 6px;
          padding-top: 5px;
          padding-left: 2px;
        }
      }
    }
  }
  .tab-content {
    .scrollView {
      height: 84vh;
    }
    .wrap {
      width: 100%;
      padding: 0 10px;
      box-sizing: border-box;
    }
  }
  .bottom_btn_wrap {
    position: fixed;
    bottom: 0px;
    width: 100%;
    display: flex;
    justify-content: space-around;
    .button {
      width: 264px;
      height: 126px;
      background-repeat: no-repeat;
      background-size: 100%;
      background-position: center;
      // background-color: $uni-text-color-theme;
      // border-radius: $uni-border-radius-bg;
    }
  }
  .fbqz {
    background-image: url("/pages2/static/images/mffbqz.png");
  }
  .glqz {
    background-image: url("/pages2/static/images/glqzxq.png");
  }
  .fbzg {
    background-image: url("/pages2/static/images/mfbbzg.png");
  }
  .glzg {
    background-image: url("/pages2/static/images/glqzxq.png");
  }
  .popup-content {
    height: 308px;
    background: #f7f7f7;
    border-radius: 10px;
    .title {
      width: 100%;
      height: 53px;
      text-align: center;
      font-size: 16px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #333333;
      background-color: #fff;
      line-height: 53px;
      border-radius: 10px 10px 0 0;
    }
    .content {
      .item {
        width: 355px;
        height: 91px;
        border-radius: 10px 10px 10px 10px;
        opacity: 1;
        margin: 15px auto 0;
        display: flex;
        .left {
          width: 199px;
          .h2 {
            display: flex;
            align-items: center;
            font-size: 22px;
            font-family: PingFang SC-Semibold, PingFang SC;
            font-weight: 600;
            color: #ffffff;
            padding: 16px 0 0 21px;
            .iconfont {
              margin-left: 10px;
            }
          }
          .desc {
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #ffe6cf;
            padding: 5px 0 0 21px;
          }
        }
        .right {
          width: 136px;
          height: 100%;
          image {
            width: 100%;
            height: 100%;
          }
        }
        button {
          width: 100%;
          height: 100%;
          background: transparent;
          padding: 0;
        }
      }
      .item1 {
        // background: #ff8822;
        button {
          width: 355px;
          height: 91px;
          background-image: url("@/static/images/common/wyzgz.png");
          background-position: center;
          background-size: 100% 100%;
          background-repeat: no-repeat;
        }
      }
      .item2 {
        background: #f8ece1;
        button {
          width: 355px;
          height: 91px;
          background-image: url("@/static/images/common/wyzyg.png");
          background-position: center;
          background-size: 100% 100%;
          background-repeat: no-repeat;
        }
        // .left {
        //   .h2 {
        //     color: #333333;
        //     .iconfont {
        //       color: #aca9a7;
        //     }
        //   }
        //   .desc {
        //     color: #b6b2af;
        //   }
        // }
      }
    }
  }
}
</style>
